﻿using System;
//=========================================
//
// 作 者：LsongStudio
// 邮 箱：song940@gmail.com
// 博 客：http://lsongs.host.sk/
// 时 间：2010-11-24 18:37:56
//
//=========================================
namespace VirusCleaner.Download
{
    
    #region 下载文件
    public class Downloader
    {        
        public delegate void ProgressChangedEvent(long value, long max);

        //public event ProgressChangedEvent ProgressChanged;


        /// <summary>        
        /// 下载文件        
        /// </summary>        
        /// <param name="url">下载文件地址</param>
        /// <param name="filename"></param>
        /// <param name="progress"></param>
        public void DownloadFile(string url, string filename, ProgressChangedEvent progress)
        {
            try
            {
                var myrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                var myrp = (System.Net.HttpWebResponse)myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                var by = new byte[1024];
                if (st != null)
                {
                    int osize = st.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        totalDownloadedByte = osize + totalDownloadedByte;
                        System.Windows.Forms.Application.DoEvents();
                        so.Write(by, 0, osize);
                        progress(totalDownloadedByte, totalBytes);
                        osize = st.Read(by, 0, (int)by.Length);
                    }
                }
                so.Close();
                if (st != null) st.Close();
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("执行下载任务错误:" + ex.Message);
            }
        }
    }
    #endregion
}
